﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Translate
{
    class BaiDu_TranslateHandle:TranslateHandle
    {
        protected override string getSign()
        {
            string sign = string.Format("{0}{1}{2}{3}", "20190612000306732", need_Tslt, "1435660288", "Xiorq8HxOIwiVHn2la_W");
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }

        protected override string GetJson()
        {
            var client = new RestClient("http://api.fanyi.baidu.com");
            var request = new RestRequest("/api/trans/vip/translate", Method.GET);
            request.AddParameter("q", need_Tslt);
            request.AddParameter("from", "en");
            request.AddParameter("to", "zh");
            request.AddParameter("appid", "20190612000306732");
            request.AddParameter("salt", "1435660288");
            request.AddParameter("sign", getSign());
            IRestResponse response = client.Execute(request);
            return response.Content;
        }

        public override string GetResult()
        {
            try
            {
                var lst = new List<string>();
                var content = GetJson();
                dynamic json = JsonConvert.DeserializeObject(content);
                foreach (var item in json.trans_result)
                {
                    lst.Add(item.dst.ToString());
                }
                return string.Join("\r\n", lst);
            }
            catch (Exception)
            {
                return "翻译失败";
            }

        }
    }
}
